package com.rising.face.ali.bishi.lrucache;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @Author: rising
 * @Description:
 * @Date: create in 2021/2/28 19:46
 */
public class LRUCacheService<K, V> {

    //负载因子使用默认的0.75
    private final float loadFactory = 0.75f;
    //缓存map
    private LinkedHashMap<K, V> cacheMap;

    //设置缓存容量，并重写removeEldestEntry
    public LRUCacheService(int maxCacheSize) {
        //HashMap达到容量就进行扩容，if ((size >= threshold)，因此需要 +1
        int capacity = (int)Math.ceil(maxCacheSize / this.loadFactory) + 1;

        cacheMap = new LinkedHashMap<K, V>(capacity, loadFactory, true) {
            //重写removeEldestEntry，当容量超过maxCacheSize会移除first
            @Override
            protected boolean removeEldestEntry(Map.Entry eldest) {
                return size() > maxCacheSize;
            }
        };
    }

    public synchronized void put(K key, V value) {
        cacheMap.put(key, value);
    }

    public synchronized V get(K key) {
        return cacheMap.get(key);
    }

    public synchronized void remove(K key) {
        cacheMap.remove(key);
    }

    public synchronized boolean contain(K key) {
        return cacheMap.containsKey(key);
    }


    public static void main(String[] args) {
        LRUCacheService<String, String> lru = new LRUCacheService<String, String>(2);
        lru.put("A", "A");
        lru.put("B", "B");
        System.out.println("lru包含key为A的: " + lru.contain("A"));
        System.out.println("A = " + lru.get("A"));
        lru.put("C", "C");
        System.out.println("lru包含key为A的: " + lru.contain("A"));
        lru.put("B", "D");
        System.out.println("lru包含key为A的: " + lru.contain("A"));
        System.out.println("lru包含key为B的: " + lru.contain("B"));
        System.out.println("lru包含key为C的: " + lru.contain("C"));
        lru.put("A", "C");
        System.out.println("lru包含key为C的: " + lru.contain("C"));
    }
}
